const axios = require('axios');

// 尝试加载nodemailer，如果未安装则设为null
let nodemailer;
try {
  nodemailer = require('nodemailer');
} catch (error) {
  console.log('nodemailer未安装，将使用备用邮件发送方案');
  nodemailer = null;
}

// 邮件服务配置
const emailConfig = {
  qq: {
    host: 'smtp.qq.com',
    port: 465,
    secure: true, // 使用SSL
    auth: {
      user: process.env.EMAIL_USER || '491829247@qq.com', // QQ邮箱地址
      pass: process.env.EMAIL_PASS || 'rytujrmnfjntbjbf' // QQ邮箱授权码（不是密码）
    },
    // 添加额外的配置选项
    tls: {
      rejectUnauthorized: false
    }
  },
}

// 创建邮件传输器
function createTransporter(provider = 'qq') {
  if (!nodemailer) {
    throw new Error('nodemailer未安装，无法创建SMTP传输器');
  }

  const config = emailConfig[provider];
  if (!config) {
    throw new Error(`不支持的邮件服务提供商: ${provider}`);
  }

  if (!config.auth.user || !config.auth.pass) {
    throw new Error(`请配置${provider}邮箱的用户名和授权码`);
  }

  return nodemailer.createTransport(config);
}

// 生成6位数字验证码
function generateVerificationCode() {
  return Math.floor(100000 + Math.random() * 900000).toString();
}

// 备用邮件发送方案（使用原有API）
async function sendEmailViaAPI(email, code, username) {
  try {
    // 尝试POST方式发送
    const response = await axios.post('https://ygwyy.top/邮箱/index.php', {
      user: username,
      email: email,
      code: code // 添加验证码参数
    }, {
      timeout: 10000,
      headers: {
        'Content-Type': 'application/json'
      }
    });

    console.log('备用API发送邮件成功:', response.data);
    return {
      success: true,
      message: code,
      method: 'api'
    };
  } catch (postError) {
    console.log('POST方式失败，尝试GET方式:', postError.message);
    
    // 如果POST失败，尝试GET方式（原有方式）
    try {
      const getResponse = await axios.get(`https://ygwyy.top/邮箱/index.php?email=${encodeURIComponent(email)}&username=${encodeURIComponent(username)}&code=${encodeURIComponent(code)}`, {
        timeout: 10000
      });
      
      console.log('备用API GET方式发送邮件成功:', getResponse.data);
      return {
        success: true,
        message: code,
        method: 'api-get'
      };
    } catch (getError) {
      console.error('备用API GET方式也失败:', getError.message);
      throw getError;
    }
  }
}

// 发送验证码邮件
async function sendVerificationEmail(email, code, username, provider = 'qq') {
  // 优先尝试使用nodemailer发送
  if (nodemailer) {
    try {
      const transporter = createTransporter(provider);

      const mailOptions = {
        from: `"智慧助农" <${emailConfig[provider].auth.user}>`,
        to: email,
        subject: '智慧助农 - 邮箱验证码',
        html: `
          <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #ddd; border-radius: 10px;">
            <h2 style="color: #4CAF50; text-align: center;">智慧助农</h2>
            <h3 style="color: #333;">邮箱验证码</h3>
            <p>尊敬的用户 <strong>${username}</strong>，您好！</p>
            <p>您正在进行邮箱验证，验证码为：</p>
            <div style="background-color: #f5f5f5; padding: 15px; text-align: center; margin: 20px 0; border-radius: 5px;">
              <span style="font-size: 24px; font-weight: bold; color: #4CAF50; letter-spacing: 3px;">${code}</span>
            </div>
            <p style="color: #666;">验证码有效期为10分钟，请及时使用。</p>
            <p style="color: #666;">如果这不是您的操作，请忽略此邮件。</p>
            <hr style="border: none; border-top: 1px solid #eee; margin: 20px 0;">
            <p style="color: #999; font-size: 12px; text-align: center;">此邮件由智慧助农系统自动发送，请勿回复。</p>
          </div>
        `
      };

      const result = await transporter.sendMail(mailOptions);
      console.log('SMTP邮件发送成功:', result.messageId);

      return {
        success: true,
        message: code,
        method: 'smtp',
        messageId: result.messageId
      };
    } catch (error) {
      console.error('SMTP邮件发送失败，尝试备用方案:', error.message);
      // 如果SMTP发送失败，回退到备用方案
    }
  }

  // 使用备用API方案
  return await sendEmailViaAPI(email, code, username);
}

// 验证邮件服务器连接
async function testEmailConnection(provider = 'qq') {
  if (!nodemailer) {
    console.log('nodemailer不可用，无法测试SMTP连接，将使用备用API方案');
    return false;
  }

  try {
    const transporter = createTransporter(provider);
    await transporter.verify();
    console.log(`${provider} 邮件服务器连接成功`);
    return true;
  } catch (error) {
    console.error(`${provider} 邮件服务器连接失败:`, error);
    return false;
  }
}

module.exports = {
  createTransporter,
  generateVerificationCode,
  sendVerificationEmail,
  sendEmailViaAPI,
  testEmailConnection,
  emailConfig
};